<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="Netty是一款非常优秀的网络编程框架，是对NIO的二次封装，本文将重点剖析Netty客户端的启动流程，深入底层了解如何使用NIO编程客户端。 本文是笔者基于问题的启发式源码阅读技巧的展示，请带着如下问题开始本文的阅读：  Netty是如何将客户端的事件加入到事件链中？ Netty客户端在启动时需要注册读事件？ Netty客户端在启动时需要注册写事件？ 如果让你基于NIO写一个客户端需要实现的关键">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty进阶：手把手教你如何编写一个NIO客户端">
<meta property="og:url" content="https://www.codingw.net/posts/76ab8a6b.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="Netty是一款非常优秀的网络编程框架，是对NIO的二次封装，本文将重点剖析Netty客户端的启动流程，深入底层了解如何使用NIO编程客户端。 本文是笔者基于问题的启发式源码阅读技巧的展示，请带着如下问题开始本文的阅读：  Netty是如何将客户端的事件加入到事件链中？ Netty客户端在启动时需要注册读事件？ Netty客户端在启动时需要注册写事件？ 如果让你基于NIO写一个客户端需要实现的关键">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210121213057784.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210121214929305.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210121223152756.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210121224450572.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210121225407845.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210121231001723.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210121232021382.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210123215108397.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210123221908421.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2021012322573249.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210123230411135.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210123231714544.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210121223152756.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210123233327899.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2021012323434047.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210123235116476.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210123235729734.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210124104542925.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210124105235773.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210101213844526.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="article:published_time" content="2021-01-27T14:47:09.000Z">
<meta property="article:modified_time" content="2021-04-26T12:33:19.923Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20210121213057784.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/76ab8a6b.html"/>





  <title>Netty进阶：手把手教你如何编写一个NIO客户端 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/76ab8a6b.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Netty进阶：手把手教你如何编写一个NIO客户端</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-01-27T22:47:09+08:00">
                2021-01-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/netty/" itemprop="url" rel="index">
                    <span itemprop="name">netty</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/76ab8a6b.html" class="leancloud_visitors" data-flag-title="Netty进阶：手把手教你如何编写一个NIO客户端">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>Netty是一款非常优秀的网络编程框架，是对NIO的二次封装，本文将重点剖析Netty客户端的启动流程，深入底层了解如何使用NIO编程客户端。</p>
<p>本文是笔者<strong>基于问题的启发式源码阅读技巧的展示</strong>，请带着如下问题开始本文的阅读：</p>
<ul>
<li>Netty是如何将客户端的事件加入到事件链中？</li>
<li>Netty客户端在启动时需要注册读事件？</li>
<li>Netty客户端在启动时需要注册写事件？</li>
<li>如果让你基于NIO写一个客户端需要实现的关键点是什么呢？</li>
</ul>
<p><strong>上面的问题也可以这样问：在使用NIO实现客户端时该注册哪些事件？</strong></p>
<p>本节将详细学习Netty4客户端的启动流程，我们从一个Netty客户端使用示例入手。</p>
<span id="more"></span>



<h2 id="1、Netty-客户端示例"><a href="#1、Netty-客户端示例" class="headerlink" title="1、Netty 客户端示例"></a>1、Netty 客户端示例</h2><p>Netty客户端示例如下：<br><img src="https://img-blog.csdnimg.cn/20210121213057784.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>对上面的步骤一一说明如下：<br>代码@1：创建 NIO EventLoopGroup，NIO 事件轮询器。</p>
<p>代码@2：创建Bootstrap实例，Netty提供的客户端操作工具类。</p>
<p>代码@3：指定创建 Channel 类型，客户端是 NioSocketChannel。</p>
<p>代码@4：通过option方法设置网络相关属性，可多次调用。</p>
<p>代码@5：通过调用 handler 方法添加客户端的事件处理器链。具体使用匿名类 ChannelInitializer，事件处理器链中通常会包含<strong>编码器</strong>、<strong>解码器</strong>、<strong>业务处理Handler</strong>(业务处理的入口)。</p>
<p>代码@6：调用 connect 方法异步建立连接。通过调用sync()方法转同步调用，等连接成功建立后才返回。</p>
<p>代码@7：创建一个Close Future，并且同步等待关闭事件的到达。</p>
<p>代码@8：安全优雅的关闭事件线程组。在具体事件过程中并不会这么使用，而是会将连接进行缓存，例如使用一个Map按IP进行缓存，发往同一个IP的请求使用同一条连接，在需要断开连接时再调用方法。</p>
<blockquote>
<p>温馨提示：上述只是Demo级的示例，但不影响对本文的探讨，后续会给出工业级的Netty使用实战。</p>
</blockquote>
<h2 id="2、Netty客户端启动流程"><a href="#2、Netty客户端启动流程" class="headerlink" title="2、Netty客户端启动流程"></a>2、Netty客户端启动流程</h2><p>本文试图揭晓Netty客户端的启动流程，让大家从底层彻底掌握其实现细节，便于更好的使用Netty，特别是对应排障起到一个很好的技能储备。</p>
<p>Netty 客户端的启动流程入口：<br><img src="https://img-blog.csdnimg.cn/20210121214929305.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>其最终调用其 doConnect 方法。<br><img src="https://img-blog.csdnimg.cn/20210121223152756.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>代码@1：调用 initAndRegister 初始化和注册到事件选择器，可联想 NIO 中通道创建后需要注册读写事件，这里就是需要将通道注册到事件选择器，稍后会重点介绍。</p>
<p>代码@2：initAndRegister 采用了异步机制，更确切是采用了 Future模式。如果已经完成则直接调用 doConnect0 方法执行连接。</p>
<p>代码@3：否则在 Future 上注册事件监听器，等注册成功后再进行调用连接。</p>
<p>接下来会对上面两个重要步骤进行详细介绍，<strong>这里给我们使用 Future 模式提供了很好的示例</strong>。</p>
<h4 id="2-1-通道注册"><a href="#2-1-通道注册" class="headerlink" title="2.1 通道注册"></a>2.1 通道注册</h4><p>客户端在连接之前需要先将通道注册到事件选择器(Selector)中，具体事项如下图所示：<br><img src="https://img-blog.csdnimg.cn/20210121224450572.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>关键如下：<br>代码@1：调用 init 方法对通过进行初始化，稍后详细介绍。<br>代码@2：将通过注册到事件轮询器中。</p>
<h5 id="2-1-1-通道初始化"><a href="#2-1-1-通道初始化" class="headerlink" title="2.1.1 通道初始化"></a>2.1.1 通道初始化</h5><p>通道初始化其代码如下：<br><img src="https://img-blog.csdnimg.cn/20210121225407845.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>代码@1：将用户定义的Handler加入到事件处理器链(ChannelPipeline)，这里非常关键：客户端在启动时我们是通过 Bootstrap 的 handler 方法设置事件链。<br>代码@2、3主要是设置网络选项、属性。</p>
<p><strong>思考题：Netty是如何将客户端定义的多个Handler加入到事件链中呢？</strong></p>
<p>这个问题其实的<strong>本质</strong>是用户自定义的 <strong>ChannelInitializer 的 initChannel 方法</strong>在什么时候调用。</p>
<p>要解开该问题，我们就需要来看一下 ChannelInitializer。<br><img src="https://img-blog.csdnimg.cn/20210121231001723.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>上面图的几个关键点：</p>
<ul>
<li>将Handler 加入到 ChannelPipeline 时其 handlerAdded 方法会被调用，其逻辑是如果该通道已经被注册到事件处理器则调用 initChannel 方法。</li>
<li>通道被注册到事件选择器(Selector)时会调用。</li>
<li>initChannel 方法支持幂等，保证一个通道的 initChannel 方法不会被多次调用。</li>
</ul>
<h5 id="2-1-2-通道注册"><a href="#2-1-2-通道注册" class="headerlink" title="2.1.2 通道注册"></a>2.1.2 通道注册</h5><p>通道注册的入口方法：SingleThreadEventLoop。<br><img src="https://img-blog.csdnimg.cn/20210121232021382.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>NIO 的最终入口为 AbstractChannel 的内部类 AbstractUnsafe 的 register 的方法。<br><img src="https://img-blog.csdnimg.cn/20210123215108397.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br><strong>这里无不透漏着Netty一个非常重要的编程技巧：一个通道会持有一个事件选择器(EventLoop)，如果调用通道的方法的线程不是EventLoop，则会把任务提交到EventLoop中执行。</strong></p>
<p>接下来重点看一下register0 方法，非常关键的一个方法。<br><img src="https://img-blog.csdnimg.cn/20210123221908421.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>代码@1：进行底层NIO层面的注册，最终调用 AbstractNio 的 doRegister。<br><img src="https://img-blog.csdnimg.cn/2021012322573249.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br><strong>注意：通道注册，其注册的OP为0，并没有关注任何的事件(读、写等)<strong>，</strong>那问题来了，读写等事件在什么时候注册呢？</strong></p>
<p>代码@2：触发 handlerAdd 事件，因为在介绍ChannelInitializer handlerAdd事件执行的条件是通道已注册，如果未注册会将任务先挂起，这里就是触发其执行。</p>
<p>代码@3：传播通道注册事件，即在调用底层 NIO 的 register 方法将通道注册到事件选择器(Selector)后传播注册事件。</p>
<p>代码@4：如果通道激活并且是首次注册，则传播通道<strong>激活事件</strong>。</p>
<p>代码@5：如果通道不是首次注册并且开启了<strong>自动注册读事件</strong>，则自动为通道注册读事件。beginRead 方法最终会调用 AbstractNioChannel 的如下方法，底层使用了NIO的 selectionKey.interestOps 方法。<br><img src="https://img-blog.csdnimg.cn/20210123230411135.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>通道的注册流程就介绍到这里了。</p>
<p><strong>在NIO中，如果不注册读事件，不会从底层网络中读取数据，则对应客户端来说就不会去处理响应包，相对服务端来说不会去解析请求包，也就是无法完成请求与响应，故在NIO编程中，通道必须注册读事件。</strong></p>
<p>注册的逻辑就基本完成了，那问题来了，虽然开启了自动注册读事件，但初次注册时只是传播了channelActive事件，那在何时会注册读事件呢？</p>
<p>原理在传播 channelActive 事件后，在开启了自动注册读事件后自动注册读事件，其代码在 DefaultChannelPipeline 中内部类 HeadContext 的 channelActive 方法，其代码截图如下：<br><img src="https://img-blog.csdnimg.cn/20210123231714544.png#pic_center" alt="在这里插入图片描述"></p>
<h4 id="2-2-连接服务端"><a href="#2-2-连接服务端" class="headerlink" title="2.2 连接服务端"></a>2.2 连接服务端</h4><p>在来看一下客户端的启动核心方法：<br><img src="https://img-blog.csdnimg.cn/20210121223152756.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>在完成了通道的初始化并注册到事件选择器后，接下来就需要向服务端发起连接操作，最终调用 doConnect0 方法，其基本的调用链如下图所示：<br><img src="https://img-blog.csdnimg.cn/20210123233327899.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>故接下来我们重点从 AbstractNioUnsafe 的 connect 方法进行深入追踪。<br><img src="https://img-blog.csdnimg.cn/2021012323434047.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>上面的方法几个关键点如下：</p>
<ul>
<li>获取通道是否激活。</li>
<li>调用内部的doConnect 完成连接，将调用底层NIO相关的方法，从该方法可以学习如何编写NIO的连接代码，稍后会详细介绍。</li>
<li>由于NIO都是非阻塞的，<strong>doConnect</strong> 方法返回后并不代表通道已成功连接到服务端，故需要开启一个定时任务进行跟踪(<strong>连接超时时间</strong>)。</li>
</ul>
<p>接下来我们详细介绍一下如何使用NIO编写连接代码。<br><img src="https://img-blog.csdnimg.cn/20210123235116476.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>代码@1：客户端连接服务端，通常是采用随机端口，当如果需要绑定到指定端口，调用 SocketChannel 的 bind 方法即可。</p>
<p>代码@2：调用底层 NIO 的 connect 方法，注意该方法并不会阻塞，返回成功表示连接建立成功；返回 false 表示还在连接中。</p>
<p>代码@3：如果是连接中，则注册OP_CONNECT事件，等连接成功后会收到对应的事件。</p>
<p>注册 OP_CONNECT 事件后，在事件选择器 NioEventLoop 的事件处理流程中会专门处理 OP_CONNECT 事件：<br><img src="https://img-blog.csdnimg.cn/20210123235729734.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>NIO模式代码最终调用 NioSocketChannel 的 doFinishConnect 方法：<br><img src="https://img-blog.csdnimg.cn/20210124104542925.png#pic_center" alt="在这里插入图片描述"><br>该方法通道在非阻塞模式下，如果连接未成功建立会返回false，由于这里是基于事件选择的，是在连接成功创建后才会触发，故这里只是简单的进行校验连接是否成功建立。</p>
<p>最后通道成功建立，需要触发通道激活事件，见下图所示：<br><img src="https://img-blog.csdnimg.cn/20210124105235773.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="AbstractNioChannel#fulfillConnectPromise"><br><strong>行文至此开头部门提出的问题都得到了针对性的解答</strong>，为了倒逼读者朋友门真正能理解开头部分的问题，<strong>建议读者进行总结，真正做到带着问题阅读源码</strong>，当然可以加笔者私信：dingwpmz，共同交流探讨。</p>
<hr>
<p>欢迎加笔者微信号(<strong>dingwpmz</strong>)，拉您如技术交流加群探讨，关注『中间件兴趣圈』回复<strong>【PDF】</strong>可获取海量学习资料。<br><img src="https://img-blog.csdnimg.cn/20210101213844526.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"></p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/2e7bc25b.html" rel="next" title="Dubbo的设计理念原来就藏在这三张图中">
                <i class="fa fa-chevron-left"></i> Dubbo的设计理念原来就藏在这三张图中
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/ea6d8964.html" rel="prev" title="面试时遇到一致性哈希算法这样回答会让面试官眼前一亮">
                面试时遇到一致性哈希算法这样回答会让面试官眼前一亮 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81Netty-%E5%AE%A2%E6%88%B7%E7%AB%AF%E7%A4%BA%E4%BE%8B"><span class="nav-number">1.</span> <span class="nav-text">1、Netty 客户端示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81Netty%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%90%AF%E5%8A%A8%E6%B5%81%E7%A8%8B"><span class="nav-number">2.</span> <span class="nav-text">2、Netty客户端启动流程</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-%E9%80%9A%E9%81%93%E6%B3%A8%E5%86%8C"><span class="nav-number">2.0.1.</span> <span class="nav-text">2.1 通道注册</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#2-1-1-%E9%80%9A%E9%81%93%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="nav-number">2.0.1.1.</span> <span class="nav-text">2.1.1 通道初始化</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-1-2-%E9%80%9A%E9%81%93%E6%B3%A8%E5%86%8C"><span class="nav-number">2.0.1.2.</span> <span class="nav-text">2.1.2 通道注册</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-%E8%BF%9E%E6%8E%A5%E6%9C%8D%E5%8A%A1%E7%AB%AF"><span class="nav-number">2.0.2.</span> <span class="nav-text">2.2 连接服务端</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
